# 重写自定义认证方法
import re
from django.contrib.auth.backends import ModelBackend
from meiduo.models import Users


def get_user_by_acoount(acoount):
    try:
        if re.match(r"^1[3-9]\d{9}", acoount):
            user = Users.objects.get(mobile=acoount)
        else:
            user = Users.objects.get(username=acoount)
    except Users.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileBackend(ModelBackend):

    def authenticate(self, username=None, password=None, **kwargs):
        """重写认证方法"""
        # 查询用户
        user = get_user_by_acoount(username)

        # 如果查询到用户，校验密码
        if user and user.check_password(password):
            # 返回user
            return user
        else:
            return None

